package pl.edu.agh.io.gpstracker.client.widget;

import java.util.LinkedHashMap;
import java.util.List;

import pl.edu.agh.io.gpstracker.client.action.AddNewTrackAction;
import pl.edu.agh.io.gpstracker.client.action.FindAllUsersAction;
import pl.edu.agh.io.gpstracker.client.dto.TrackDto;
import pl.edu.agh.io.gpstracker.client.dto.UserDto;
import pl.edu.agh.io.gpstracker.client.dto.UserType;
import pl.edu.agh.io.gpstracker.client.result.CollectionResult;
import pl.edu.agh.io.gpstracker.client.result.VoidResult;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;

public class NewTrackWidget extends GenericWidget {

	private static final String USER_NAME = "userName";
	private static final String LAT = "lat";
	private static final String LONG = "long";
	private static final String NAME = "name";

	private DynamicForm form;
	private ListGrid trackElements;
	private SelectItem usersSelectItem;
	private TextItem name;
	private TextItem longtitude;
	private TextItem latitude;
	private List<UserDto> usersList;

	@Override
	protected void onInit() {
		super.onInit();
		createWidget();
	}
	


	private void createWidget() {
		form = new DynamicForm();
		form.setNumCols(6);
		trackElements = new ListGrid();

		ListGridField nameF = new ListGridField(NAME, "Nazwa punktu przejazdu");
		ListGridField longtitudeF = new ListGridField(LONG, "Dlugosc");
		ListGridField latitudeF = new ListGridField(LAT, "Szerokosc");
		trackElements.setFields(nameF, longtitudeF, latitudeF);

		name = new TextItem(NAME, "Nazwa punktu przejazdu");
		name.setRequired(true);
		longtitude = new TextItem(LONG, "Dlugosc");
		longtitude.setRequired(true);
		latitude = new TextItem(LAT, "Szerokosc");
		latitude.setRequired(true);

		usersSelectItem = new SelectItem(USER_NAME, "Nazwa uzytkwonika");
		IButton saveTrack = new IButton("Zapisz trase");
		saveTrack.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				saveTrack();
			}
		});

		IButton addNewPosition = new IButton("Dodaj punkt przejazdu");
		addNewPosition.setWidth(200);
		addNewPosition.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (form.validate()) {
					// zapisuje
					ListGridRecord record = new ListGridRecord();
					record.setAttribute(NAME, name.getValueAsString());
					record.setAttribute(LONG, latitude.getValueAsString());
					record.setAttribute(LAT, longtitude.getValueAsString());
					trackElements.addData(record);
					trackElements.refreshFields();
				}
			}
		});
		IButton removePosition = new IButton("Usun punkt przejazdu");
		removePosition.setWidth(200);
		removePosition.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (trackElements.getSelectedRecord() == null) {
					SC.say("Nie wybrano punktu!");
				} else {
					trackElements.removeSelectedData();
				}
			}
		});
		HLayout buttonLayout = new HLayout();
		buttonLayout.setAlign(Alignment.RIGHT);
		buttonLayout.setMembers(addNewPosition, removePosition, saveTrack);
		buttonLayout.setMembersMargin(5);
		form.setFields(name, longtitude, latitude, usersSelectItem);
		setMembers(trackElements, form, buttonLayout);
	}

	@Override
	protected void onDraw() {
		super.onDraw();
		loadUsers();
	}

	private void saveTrack() {
		final TrackDto track = new TrackDto();
		track.setName(createTrackName());
		
		
		for (UserDto user: usersList){
			if (user.getId().equals(Integer.parseInt( ( String)usersSelectItem.getValue()))){
				track.setUser(user);
			    break;
			}
		}

		dispatcher.execute(new AddNewTrackAction(track),
				new AsyncCallback<VoidResult>() {

					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(VoidResult result) {
						SC.say("Trasa <b>" + track.getName()
								+ "</b> dla uzytkownika <b>"
								+ track.getUser().getLogin()
								+ " </b> zostala dodana!");

						form.clearValues();
						trackElements.setData(new ListGridRecord[0]);
					}
				});
	}

	private String createTrackName() {
		StringBuffer sb = new StringBuffer();
		int iloopNumber = 0;
		for (ListGridRecord record : trackElements.getRecords()) {
			sb.append(record.getAttribute(NAME));
			iloopNumber++;
			if (iloopNumber < trackElements.getRecords().length) {
				sb.append("-");
			}
		}
		return sb.toString();
	}

	public void loadUsers() {
		dispatcher.execute(new FindAllUsersAction(UserType.MOBILE_USER),
				new AsyncCallback<CollectionResult<UserDto>>() {

					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(CollectionResult<UserDto> result) {
						LinkedHashMap<String, String> users = new LinkedHashMap<String, String>();

						for (UserDto user : result.getResult()) {
							users.put(String.valueOf(user.getId()), user
									.getLogin());
						}
						usersSelectItem.setValueMap(users);
						usersList = result.getResult();
					}
				});
	}
}
